package cn.wmingming.e3mall.item.controller;

import cn.wmingming.e3mall.item.pojo.Item;
import cn.wmingming.e3mall.item.utils.FreeMarkerUtil;
import cn.wmingming.e3mall.manager.service.ItemService;
import cn.wmingming.e3mall.pojo.TbItem;
import cn.wmingming.e3mall.pojo.TbItemDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Huangzm
 * @create 2018/06/13 8:52
 * @desc 商品详情信息页面控制器
 * @Modified By:
 **/
@Controller
public class ItemController {
    @Autowired
    private ItemService itemService;
    @Value("${FREEMARKER_PATH}")
    private String path;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @RequestMapping("item/{itemId}")
    public String showItemPage(@PathVariable Long itemId, Model model){
        //先判断是否有本地静态页面
        File file = new File(path+itemId+".html");
        if(file.exists()){
            return "redirect:http://www.localhost/item/"+itemId+".html";
        }else {

            //查询商品数据和商品描述数据
            TbItem tbItem = itemService.getItemById(itemId);
            if(tbItem == null){
                return "error/exception";
            }
            Item item = new Item(tbItem);
            //item.setId(itemId);
            TbItemDesc itemDesc = itemService.getItemDesc(itemId);
            //放到model里面
            model.addAttribute("item",item);
            model.addAttribute("itemDesc",itemDesc);

            //生成静态页面，供下次访问
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("item",item);
            map.put("itemDesc",itemDesc);
            //生成文件的路径和名称
            String outputFile = path + itemId+ ".html";
            //生成静态页面
            FreeMarkerUtil.generateStaticHtml(map,freeMarkerConfigurer,outputFile,"item.ftl");
            return "item";
        }

    }
}
